<!DOCTYPE html>
<!--
Copyright (c) 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/base.html">
<link rel="import" href="/tracing/base/math/rect.html">

<script>
'use strict';

tr.exportTo('tr.ui.b', function() {
  function instantiateTemplate(selector, doc) {
    doc = doc || document;
    const el = Polymer.dom(doc).querySelector(selector);
    if (!el) {
      throw new Error('Element not found: ' + selector);
    }
    return doc.importNode(el.content, true);
    //    return el.createInstance();
  }

  function windowRectForElement(element) {
    const position = [element.offsetLeft, element.offsetTop];
    const size = [element.offsetWidth, element.offsetHeight];
    let node = element.offsetParent;
    while (node) {
      position[0] += node.offsetLeft;
      position[1] += node.offsetTop;
      node = node.offsetParent;
    }
    return tr.b.math.Rect.fromXYWH(position[0], position[1], size[0], size[1]);
  }

  function scrollIntoViewIfNeeded(el) {
    const pr = el.parentElement.getBoundingClientRect();
    const cr = el.getBoundingClientRect();
    if (cr.top < pr.top) {
      el.scrollIntoView(true);
    } else if (cr.bottom > pr.bottom) {
      el.scrollIntoView(false);
    }
  }

  function extractUrlString(url) {
    let extracted = url.replace(/url\((.*)\)/, '$1');

    // In newer versions of chrome, the contents of url() will be quoted. Remove
    // these quotes as well. If quotes are not present, match will fail and this
    // becomes a no-op.
    extracted = extracted.replace(/\"(.*)\"/, '$1');

    return extracted;
  }

  function toThreeDigitLocaleString(value) {
    return value.toLocaleString(
        undefined, {minimumFractionDigits: 3, maximumFractionDigits: 3});
  }

  return {
    toThreeDigitLocaleString,
    instantiateTemplate,
    windowRectForElement,
    scrollIntoViewIfNeeded,
    extractUrlString,
  };
});
</script>
